import pyautogui
import cv2
import numpy as np
import time
import pyperclip
from config import SEARCH_KEYWORDS, FILTER_KEYWORDS, SCREENSHOT_DIR
from PIL import Image, ImageChops
import os

# 这里建议后续完善：用模板匹配定位控件

def locate_and_click(template_path, confidence=0.8):
    """
    用模板图片定位并点击
    """
    try:
        location = pyautogui.locateCenterOnScreen(template_path, confidence=confidence)
        if location:
            pyautogui.click(location)
            time.sleep(0.5)
            return True
        return False
    except pyautogui.ImageNotFoundException:
        print(f"未找到图片: {template_path}")
        return False

def search_keyword(keyword):
    """
    在QQ顶部搜索框输入关键字
    """
    search_box_img = f"{SCREENSHOT_DIR}/search_box.png"
    # 每次都重新点击搜索框，确保焦点
    if locate_and_click(search_box_img):
        time.sleep(0.5)  # 等待焦点切换
        pyautogui.hotkey('ctrl', 'a')  # 全选
        pyautogui.press('backspace')   # 清空
        pyperclip.copy(keyword)
        pyautogui.hotkey('ctrl', 'v')
        pyautogui.press('enter')
        time.sleep(3)  # 等待搜索结果加载
        return True
    return False

def get_chat_records():
    """
    抓取当前聊天窗口的聊天记录（可用pyperclip复制，或OCR识别）
    """
    # 直接截图聊天区域，然后用通用OCR识别
    import os
    from screenshot_helper import take_screenshot

    # 这里假设用户已提前截图并标注聊天区域模板
    chat_area_template = os.path.join(SCREENSHOT_DIR, "chat_record.png")

    # 用模板定位聊天区域
    location = pyautogui.locateOnScreen(chat_area_template, confidence=0.8)
    if location:
        # 截取该区域
        left = int(location.left - 130)
        top = int(location.top + 50)
        width = int(location.width + 200)
        height = int(location.height + 700)

        out_path = scroll_and_capture((left, top, width, height), 5, 700, SCREENSHOT_DIR)
    else:
        print("未找到聊天区域模板(chat_area.png)，无法截图聊天内容。")
        return []

    # OCR识别
    try:
        import easyocr
        reader = easyocr.Reader(['ch_sim', 'en'])
        result = reader.readtext(out_path, detail=0)
        # 去除空行
        return result
    except Exception as e:
        print(f"OCR识别失败: {e}")
        return []
    # 这里建议后续完善
    return []

def filter_records(records):
    """
    过滤包含过滤关键字的聊天记录
    """
    filtered = []
    for record in records:
        if not any(fk in record for fk in FILTER_KEYWORDS):
            import re
            # 判断是否为yyyy/MM/dd格式的日期
            if record.strip().endswith(tuple([f"{y:04d}/{m:02d}/{d:02d}" for y in range(1900, 2100) for m in range(1, 13) for d in range(1, 32)])):
                filtered.append("------")
                filtered.append("-----------------------------------------------")
            # 判断是否以HH:mm结尾
            elif re.search(r'\d{2}:\d{2}$', record.strip()):
              filtered.append("------")
              filtered.append("-----------------------------------------------")
            # 如果以“昨天 ”结尾，则加空行
            elif record.strip().endswith("昨天"):
                filtered.append("------")
                filtered.append("-----------------------------------------------")
            # 如果以“星期一”到“星期天”结尾，则加空行
            elif any(record.strip().endswith(day) for day in ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]):
                filtered.append("------")
                filtered.append("-----------------------------------------------")
            filtered.append(record)
    return filtered

def images_are_similar(img1, img2, threshold=5):
    """
    判断两张图片是否相似（完全重复或差异极小）
    """
    diff = ImageChops.difference(img1, img2)
    bbox = diff.getbbox()
    if bbox is None:
        return True  # 完全相同
    diff_area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
    return diff_area < threshold

def scroll_and_capture(region, max_steps, scroll_px, save_dir):
    """
    滚动截图，自动检测是否到底部
    """
    images = []
    last_img = None
    for i in range(max_steps):
        img = pyautogui.screenshot(region=region)
        if last_img and images_are_similar(img, last_img):
            print("检测到底部，提前结束。")
            break
        img_path = os.path.join(save_dir, f"part_{i}.png")
        img.save(img_path)
        images.append(img_path)
        last_img = img
        pyautogui.scroll(-scroll_px)
        time.sleep(0.5)
    if not images:
        print("未截取到任何图片。")
        return None
    # 拼接图片
    imgs = [Image.open(p) for p in images]
    total_height = sum(im.height for im in imgs)
    result = Image.new(imgs[0].mode, (imgs[0].width, total_height))
    y = 0
    for im in imgs:
        result.paste(im, (0, y))
        y += im.height
    out_path = os.path.join(save_dir, "full_chat.png")
    result.save(out_path)
    print(f"已保存完整聊天截图：{out_path}")
    return out_path